package com.kld.amaptset.presenter;

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.kld.amaptset.conn.Gank;
import com.kld.amaptset.model.FunnyData;
import com.kld.amaptset.model.MeiziData;
import com.kld.amaptset.ui.IView.MainView;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by KELUNGDE on 2017/8/5.
 */

public class MainPresenter extends BasePresenter<MainView> {

    private Context mContext;

    private MainView iView;

    public MainPresenter(Context mContext, MainView iView) {
        super(mContext, iView);
        this.mContext = mContext;
        this.iView = iView;

    }

    @Override
    public void release() {

    }


    public void fabClick() {
//        mContext.startActivity(new Intent(mContext,));
        Toast.makeText(mContext, "fab-Click", Toast.LENGTH_SHORT).show();
    }

    public void fatchMeiziData(int page) {

        iView.showProgress();
        Observable.zip(Gank.getGankRetrofitInstance().getMeiziData(page),
                Gank.getGankRetrofitInstance().getFunnyData(page),
                new BiFunction<MeiziData, FunnyData, MeiziData>() {
                    @Override
                    public MeiziData apply(MeiziData meiziData, FunnyData funnyData) throws Exception {
                        return 合并数据(meiziData, funnyData);
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MeiziData>() {
                    @Override
                    public void accept(MeiziData meiziData) {
                        if (meiziData.results.size() == 0){
                            iView.showNoMoreData();//展示没有数据
                        }else {
                            iView.showMeiziList(meiziData.results);//展示mz图片
                        }
                        iView.hideProgress();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable){
                        iView.showErrorView();
                        iView.hideProgress();
                    }
                });

    }

    private MeiziData 合并数据(MeiziData meiziData, FunnyData funnyData) {
        int size = Math.min(meiziData.results.size(), funnyData.results.size());
        for (int i = 0; i < size; i++) {
            meiziData.results.get(i).desc = meiziData.results.get(i).desc + "，" + funnyData.results.get(i).desc;
            meiziData.results.get(i).who = funnyData.results.get(i).who;
        }
        return meiziData;
    }


}
